package com.hantanger.weblog.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hantanger.weblog.model.Comment;
import com.hantanger.weblog.model.Post;
import com.hantanger.weblog.util.HtmlUtil;
import com.hantanger.weblog.util.UserHelper;

public class PostSingleController extends BaseController {

	@Override
	public String doGet(HttpServletRequest request, HttpServletResponse response) {
		Long postId = HtmlUtil.getLong(request, "postId", 0L);
		boolean incViewCount = true;
		if(UserHelper.isAdmin()){
			incViewCount = false;
		}
		Post post = getPostService().getPostById(postId, incViewCount);
		if(post == null){
			request.setAttribute("errorMsg", "此篇日志不存在！");
			request.setAttribute("code", "2");
			return "error";
		}
		if(!UserHelper.isAdmin() && !(post.isPubliced()&& post.isPublished())){
			request.setAttribute("errorMsg", "此日志设置了私人访问权限!");
			request.setAttribute("code", "2");
			return "error";
		}
		request.setAttribute("post", post);
		List<Post> prevNextPosts = getPostService().getPrevNextPosts(post.getPublishTime(), true);
		request.setAttribute("prevNextPosts", prevNextPosts);
		
		long now = System.currentTimeMillis();
		List<Comment> commentList = getPostService().getParentCommentList(postId, 100, now);
		request.setAttribute("comments", commentList);
		
		if(commentList != null && commentList.size() > 0){
			long[] parentIds = new long[commentList.size()];
			for(int i=0;i<parentIds.length;i++){
				parentIds[i] = commentList.get(i).getId();
			}
			Map<Long, List<Comment>> subComments = getPostService().getSubCommentList(parentIds, 100, now);
			for(Comment parentComment : commentList){
				parentComment.setSubComments(subComments.get(parentComment.getId()));
			}
		}
		
		return "postsingle";
	}
	
	@Override
	protected void setSEO(HttpServletRequest request){
		Post post = (Post)request.getAttribute("post");
		if(post != null){
			request.setAttribute("title", post.getTitle());
			String digest = null;
			if(post.getDigest() != null){
				digest = post.getDigest().getValue();
			}
			request.setAttribute("description", digest);
			request.setAttribute("keywords", post.getKeyword());
		}
	}

}
